import { createRouter, createWebHistory } from 'vue-router'
import CustomerService from '../views/CustomerService.vue'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      redirect: '/index'
    },
    {
      path: '/index',
      component: () => import('../views/Index.vue'),
    },
    {
      path: '/:pathMatch(.*)*',
      name: 'not-found',
      component: () => import('../views/404.vue')
    },
    {
      path: '/login',
      name: 'login',
      component: () => import('../views/Login.vue')
    },
    {
      path: '/register',
      name: 'register',
      component: () => import('../views/Register.vue')
    },
    {
      path: '/businessList',
      name: 'businessList',
      component: () => import('../views/BusinessList.vue')
    },
    {
      path: '/businessInfo',
      name: 'businessInfo',
      component: () => import('../views/BusinessInfo.vue')
    },
    {
      path: '/profile',
      name: 'profile',
      component: () => import('../views/Profile.vue')
    },
    {
      path: '/address',
      name: 'address',
      component: () => import('../views/Address.vue')
    },
    {
      path: '/order',
      name: 'order',
      component: () => import('../views/Order.vue')
    },
    {
      path: '/forgot-password',
      name: 'forgot-password',
      component: () => import('../views/ForgotPassword.vue')
    },
    {
      path: '/message',
      name: 'message',
      component: () => import('../views/Message.vue')
    },
    {
      path: '/cart',
      name: 'cart',
      component: () => import('../views/Cart.vue')
    },
    {
      path: '/customer-service',
      name: 'customer-service',
      component: CustomerService
    },
    {
      path: '/message-detail/:id',
      name: 'message-detail',
      component: () => import('../views/MessageDetail.vue')
    },
    {
      path: '/payment',
      name: 'payment',
      component: () => import('../views/Payment.vue')
    },
    {
      path: '/payment/result',
      name: 'paymentResult',
      component: () => import('../views/PaymentResult.vue')
    },
    {
      path: '/review',
      name: 'review',
      component: () => import('../views/Review.vue')
    },
    {
      path: '/order-detail',
      name: 'OrderDetail',
      component: () => import('../views/OrderDetail.vue')
    }
  ],
})

router.beforeEach(function (to, from, next) {
  let user = sessionStorage.getItem('user');
  // 需要登录才能访问的路由
  const authRoutes = [
    '/profile', 
    '/address', 
    '/order', 
    '/message', 
    '/cart', 
    '/customer-service',
    '/payment',
    '/review'  // 添加评价页面到需要登录的路由列表
  ];

  if (authRoutes.includes(to.path) && !user) {
    router.push('/login');
  }
  next();
});

export default router
